<template>
  <div>
    <!-- 模块选择 -->
    <div class="module-selector">
      <el-radio-group v-model="activeModule" @change="handleModuleChange">
        <el-radio-button label="teacher">教师管理</el-radio-button>
        <el-radio-button label="student">学生管理</el-radio-button>
        <el-radio-button label="parent">家长管理</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="query">
        <el-form-item v-for="item in searchOptions[activeModule]" :key="item.prop" :label="item.label">
          <el-input
              v-if="item.type === 'input'"
              v-model="query[item.prop]"
              :placeholder="`请输入${item.label}`"
              clearable
          />
          <el-select
              v-else-if="item.type === 'select'"
              v-model="query[item.prop]"
              :placeholder="`请选择${item.label}`"
              clearable
              style="width: 150px"
          >
            <el-option
                v-for="opt in item.options"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="container">
      <!-- 工具栏按钮 -->
      <div class="toolbar-container">
        <el-button type="primary" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          批量删除
        </el-button>
      </div>

      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column
            type="selection"
            width="55"
            align="center"
        />

        <!-- 序号列 -->
        <el-table-column
            type="index"
            label="序号"
            width="55"
            align="center"
        />

        <!-- 动态渲染普通列 -->
        <template v-for="column in columns[activeModule]">
          <el-table-column
              v-if="!['selection', 'index', 'operator'].includes(column.type)"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :formatter="column.formatter"
          />
        </template>

        <!-- 操作列 -->
        <el-table-column
            label="操作"
            width="220"
            fixed="right"
            align="center"
        >
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                  v-if="activeModule !== 'student'"
                  size="small"
                  @click="handleView(row)"
              >查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="page.index"
          v-model:page-size="page.size"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="changePage"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        :title="`${isEdit ? '编辑' : '新增'}${moduleNames[activeModule]}`"
        v-model="visible"
        width="700px"
        destroy-on-close
        :close-on-click-modal="false"
        @close="closeDialog"
    >
      <el-form :model="rowData" label-width="100px" ref="formRef">
        <el-form-item label="用户名" prop="username" required :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="rowData.username" />
        </el-form-item>
        <el-form-item
            v-if="!isEdit"
            label="密码"
            prop="password"
            required
            :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="rowData.password" show-password />
        </el-form-item>

        <el-form-item
            v-else
            label="修改密码"
            prop="password"
            :rules="[{ trigger: 'blur' }]"
        >
          <el-input v-model="rowData.password" show-password placeholder="如不修改密码请留空" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName" required :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
          <el-input v-model="rowData.realName" />
        </el-form-item>

        <!-- 性别下拉框（新增教师字段） -->
        <el-form-item v-if="activeModule === 'teacher'" label="性别" prop="sex" required :rules="[{ required: true, message: '请选择性别', trigger: 'change',type:'string' }]">
          <el-select v-model="rowData.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="男性" />
            <el-option label="女" value="女性" />
          </el-select>
        </el-form-item>

        <!-- 年级 -->
        <el-form-item
            v-if="activeModule === 'student'"
            label="年级"
            prop="grade"
            required
            :rules="[{ required: true, message: '请选择年级', trigger: 'change' }]">
          <el-select v-model="rowData.grade" placeholder="请选择年级" style="width: 100%">
            <el-option
                v-for="grade in gradeOptions"
                :key="grade.value"
                :label="grade.label"
                :value="grade.value"
            />
          </el-select>
        </el-form-item>

        <!-- 班级 -->
        <el-form-item
            v-if="activeModule === 'student'"
            label="班级"
            prop="classNum"
            required
            :rules="[{ required: true, message: '请选择班级', trigger: 'change' }]">
          <el-select v-model="rowData.classNum" placeholder="请选择班级" style="width: 100%">
            <el-option
                v-for="cls in classOptions"
                :key="cls.value"
                :label="cls.label"
                :value="cls.value"
            />
          </el-select>
        </el-form-item>

        <!-- 职称下拉框（仅教师） -->
        <el-form-item v-if="activeModule === 'teacher'" label="职称" prop="jobTitle" required :rules="[{ required: true, message: '请选择职称', trigger: 'change' }]">
          <el-select v-model="rowData.jobTitle" placeholder="请选择职称" style="width: 100%">
            <el-option
                v-for="title in titleOptions"
                :key="title.value"
                :label="title.label"
                :value="title.value"
            />
          </el-select>
        </el-form-item>

        <!-- 状态下拉框 -->
        <el-form-item label="状态" prop="status" required :rules="[{ required: true, message: '请选择状态', trigger: 'change' }]">
          <el-select v-model="rowData.status" placeholder="请选择状态" style="width: 100%">
            <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>


        <!-- 学生和家长特有字段 -->
        <template v-if="activeModule === 'student' || activeModule === 'parent'">
          <el-form-item label="性别" prop="sex" required :rules="[{ required: true, message: '请选择性别', trigger: 'change',type:'string' }]">
            <el-select v-model="rowData.sex" style="width: 100%">
              <el-option label="男" value="男性" />
              <el-option label="女" value="女性" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 家长特有字段 -->
<!--        <template v-if="activeModule === 'parent'">-->
<!--          <el-form-item label="绑定学生姓名" prop="studentName" required :rules="[{ required: true, message: '请输入绑定学生姓名', trigger: 'blur' }]">-->
<!--            <el-input v-model="rowData.studentName" />-->
<!--          </el-form-item>-->
<!--          <el-form-item label="绑定学生ID" prop="studentId" required :rules="[{ required: true, message: '请输入绑定学生ID', trigger: 'blur' }]">-->
<!--            <el-input v-model="rowData.studentId" />-->
<!--          </el-form-item>-->
<!--        </template>-->
        <template v-if="activeModule === 'parent'">
          <el-form-item
              v-for="(binding, index) in rowData.bindings"
              :key="index"
              :label="`绑定学生${index + 1}`"
          >
            <el-input
                v-model="binding.studentId"
                placeholder="请输入学生ID"
                @blur="fetchStudentName(binding, index)"
                style="width: 160px; margin-right: 10px"
            />
            <el-input
                v-model="binding.studentName"
                placeholder="学生姓名将自动填充"
                disabled
                style="width: 160px; margin-right: 10px"
            />
            <el-button type="danger" @click="removeBinding(index)">解除绑定</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addBinding">添加孩子</el-button>
          </el-form-item>
        </template>


      </el-form>
      <template #footer>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog :title="`${moduleNames[activeModule]}详情`" v-model="visible1" width="700px" destroy-on-close>
      <el-descriptions :column="2" border>
        <template v-for="item in viewData.list" :key="item.prop">
          <el-descriptions-item :label="item.label">
            {{ item.formatter ? item.formatter(viewData.row[item.prop]) : viewData.row[item.prop] }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import {getUserList,createUser,updateUser,deleteUser,batchDeleteUser,
        getStudentById,getParentBindingsCount} from "@/api/user";

// 模块名称映射
const moduleNames = {
  teacher: '教师',
  student: '学生',
  parent: '家长'
};

// 下拉选项数据
const gradeOptions = [
  { label: '一年级', value: 1 },
  { label: '二年级', value: 2 },
  { label: '三年级', value: 3 },
  { label: '四年级', value: 4 },
  { label: '五年级', value: 5 },
  { label: '六年级', value: 6 },
];

const classOptions = [
  { label: '1班', value: 1 },
  { label: '2班', value: 2 },
  { label: '3班', value: 3 },
  { label: '4班', value: 4 },
  { label: '5班', value: 5 },
  { label: '6班', value: 6 },
];

const statusOptions = [
  { label: '正常', value: '正常' },
  { label: '冻结', value: '冻结' },
];


const titleOptions = [
  { label: '三级教师', value: '三级教师' },
  { label: '二级教师', value: '二级教师' },
  { label: '一级教师', value: '一级教师' },
  { label: '高级教师', value: '高级教师' },
  { label: '正高级教师', value: '正高级教师' }
];

// 当前激活的模块
const activeModule = ref<'teacher' | 'student' | 'parent'>('teacher');
const formRef = ref<FormInstance>();

// 模块切换处理
const handleModuleChange = () => {
  resetSearch();
  page.index = 1;
  getData();
};

// 查询相关
const query = reactive({
  realName: '',
  grade: '',
  classNum: '',
  status: ''
});

//重置按钮
const handleReset = () => {
  resetSearch();    // 清空 query 对象
  page.index = 1;   // 重置分页页码
  getData();        // 重新获取数据
};



// 初始化新增数据
const initNewData = () => {
  const baseData = {
    username: '',
    password: '',
    realName: '',
    status: '正常' // 默认正常状态
  };

  if (activeModule.value === 'teacher') {
    return { ...baseData, jobTitle: '' };
  } else if (activeModule.value === 'student') {
    return { ...baseData, sex: '男性',grade:'',classNum:'' }; // 默认男性
  } else if (activeModule.value === 'parent') {
    return { ...baseData, sex: '男性', bindings: [{ studentId: '', studentName: '' }] };
  }
  return baseData;
};

// 获取数据
const getData = async () => {
  try {
    const params = {
      ...query,
      page: page.index,
      pageSize: page.size
    };
    const res = await getUserList(activeModule.value, params);
    // tableData.value = res.data.list;
    let list = res.data.list;

    if (activeModule.value === 'parent') {
      list = list.map(item => {
        if (item.studentNames && item.studentIds) {
          const names = item.studentNames.split(',');
          const ids = item.studentIds.split(',');
          item.studentDisplay = names.map((n, i) => `${n}（ID:${ids[i]}）`).join('，');
        } else {
          item.studentDisplay = '无';
        }
        return item;
      });
    }

    tableData.value = list;

    page.total = res.data.total;
  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};

// 不同模块的搜索选项
const searchOptions = {
  teacher: [
    { type: 'input', label: '教师姓名：', prop: 'realName' },
    {
      type: 'select',
      label: '状态：',
      prop: 'status',
      options: [
        { label: '全部', value: '' },
        { label: '正常', value: '正常' },
        { label: '冻结', value: '冻结' },
      ]
    }
  ],
  student: [
    { type: 'input', label: '学生姓名：', prop: 'realName' },
    {
      type: 'select',
      label: '年级：',
      prop: 'grade',
      options: [
        { label: '全部', value: '' },
        { label: '一年级', value: 1 },
        { label: '二年级', value: 2 },
        { label: '三年级', value: 3 },
        { label: '四年级', value: 4 },
        { label: '五年级', value: 5 },
        { label: '六年级', value: 6 }
      ]
    },
    {
      type: 'select',
      label: '班级：',
      prop: 'classNum',
      options: [
        { label: '全部', value: '' },
        { label: '1班', value: 1 },
        { label: '2班', value: 2 },
        { label: '3班', value: 3 },
        { label: '4班', value: 4 },
        { label: '5班', value: 5 },
        { label: '6班', value: 6 },
      ]
    },
    {
      type: 'select',
      label: '状态：',
      prop: 'status',
      options: [
        { label: '全部', value: '' },
        { label: '正常', value: '正常' },
        { label: '冻结', value: '冻结' },
      ]
    }
  ],
  parent: [
    { type: 'input', label: '家长姓名：', prop: 'realName' },
    // {
    //   type: 'select',
    //   label: '年级：',
    //   prop: 'grade',
    //   options: [
    //     { label: '全部', value: '' },
    //     { label: '一年级', value: 1 },
    //     { label: '二年级', value: 2 },
    //     { label: '三年级', value: 3 },
    //     { label: '四年级', value: 4 },
    //     { label: '五年级', value: 5 },
    //     { label: '六年级', value: 6 }
    //   ]
    // },
    // {
    //   type: 'select',
    //   label: '班级：',
    //   prop: 'classNum',
    //   options: [
    //     { label: '全部', value: '' },
    //     { label: '1班', value: 1 },
    //     { label: '2班', value: 2 },
    //     { label: '3班', value: 3 },
    //     { label: '4班', value: 4 },
    //     { label: '5班', value: 5 },
    //     { label: '6班', value: 6 },
    //   ]
    // },
    {
      type: 'select',
      label: '状态：',
      prop: 'status',
      options: [
        { label: '全部', value: '' },
        { label: '正常', value: '正常' },
        { label: '冻结', value: '冻结' },
      ]
    }
  ]
};

const handleSearch = () => {
  page.index = 1;
  getData();
};

const resetSearch = () => {
  Object.keys(query).forEach(key => {
    query[key] = '';
  });
};

// 表格列配置
const columns = {
  teacher: [
    { type: 'selection', width: 55, align: 'center' },
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'username', label: '用户名' },
    { prop: 'realName', label: '姓名' },
    { prop: 'jobTitle', label: '职称' },
    {
      prop: 'status',
      label: '状态',
      formatter: (row) => {
        if (row.status === '正常') return '正常';
        if (row.status === '冻结') return '冻结';
        return '未知';
      }

    },
  ],
  student: [
    { type: 'selection', width: 55, align: 'center' },
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'id',label: 'ID'},
    { prop: 'username', label: '用户名' },
    { prop: 'realName', label: '姓名' },
    {
      prop: 'sex',
      label: '性别',
      formatter: (row) => row.sex === '男性' ? '男' : '女'
    },
    { prop: 'grade', label: '年级',formatter: row => row.grade ? `${row.grade}年级` : '已毕业'},
    { prop: 'classNum', label: '班级',formatter: row => row.grade ? `${row.classNum}班` : ''   },
    {
      prop: 'status',
      label: '状态',
      formatter: (row) => {
        if (row.status === '正常') return '正常';
        if (row.status === '冻结') return '冻结';
        return '未知';
      }

    },
  ],
  parent: [
    { type: 'selection', width: 55, align: 'center' },
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'username', label: '用户名' },
    { prop: 'realName', label: '姓名' },
    {
      prop: 'sex',
      label: '性别',
      formatter: (row) => row.sex === '男性' ? '男' : '女'
    },
    { prop: 'bindingCount', label: '绑定学生个数' },
    // { prop: 'studentName', label: '绑定学生' },
    // { prop: 'studentId', label: '绑定学生ID' },
    // { prop: 'grade', label: '年级',formatter: row => row.grade ? `${row.grade}年级` : '已毕业'},
    // { prop: 'classNum', label: '班级', formatter: row => row.grade ? `${row.classNum}班` : '' },
    {
      prop: 'status',
      label: '状态',
      formatter: (row) => {
        if (row.status === '正常') return '正常';
        if (row.status === '冻结') return '冻结';
        return '未知';
      }

    },
  ]
};

// 分页相关
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});

const tableData = ref([]);
const selectedIds = ref([]);

const changePage = (val: number) => {
  page.index = val;
  getData();
};

const handleSizeChange = (val: number) => {
  page.size = val;
  page.index = 1;
  getData();
};

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }

  ElMessageBox.confirm(`确定要删除选中的${selectedIds.value.length}条${moduleNames[activeModule.value]}数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await batchDeleteUser(activeModule.value, selectedIds.value);
    ElMessage.success('删除成功');
    getData();
    selectedIds.value = [];
  }).catch(() => {});
};

// 弹窗相关
const visible = ref(false);
const visible1 = ref(false);
const isEdit = ref(false);
const rowData = ref<any>({});
const viewData = ref({
  row: {},
  list: []
});

// 新增按钮点击
const handleAdd = () => {
  isEdit.value = false;
  rowData.value = initNewData();
  visible.value = true;
};

// 编辑按钮点击
const handleEdit = (row: any) => {
  isEdit.value = true;

  //过滤掉密码字段，避免回显
  const { password, ...rest } = row;
  rowData.value = { ...rest };

  if (activeModule.value === 'parent') {
    // 初始化 bindings
    if (row.studentIds && row.studentNames) {
      const studentIds = row.studentIds.split(',');
      const studentNames = row.studentNames.split(',');
      rowData.value.bindings = studentIds.map((id, index) => ({
        studentId: id,
        studentName: studentNames[index] || ''
      }));
    } else {
      rowData.value.bindings = [];
    }
  }

  visible.value = true;
};

// 确认提交
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();

    const role = activeModule.value;

    if (activeModule.value === 'parent') {
      rowData.value.studentIds = rowData.value.bindings.map(b => b.studentId);
    }

    if (isEdit.value) {
      // 编辑
      await updateUser(role, rowData.value);
      ElMessage.success('编辑成功');
    } else {
      // 新增
      await createUser(role, rowData.value);
      ElMessage.success('新增成功');
    }

    visible.value = false;
    getData();
  } catch (error) {
    console.log('操作失败', error);
  }

};

const closeDialog = () => {
  visible.value = false;
};

// 查看详情
const handleView = (row: any) => {
  viewData.value.row = { ...row };

  if (activeModule.value === 'teacher') {
    viewData.value.list = [
      { prop: 'id', label: 'ID' },
      { prop: 'username', label: '用户名' },
      { prop: 'realName', label: '姓名' },
      { prop: 'sex', label: '性别'},
      { prop: 'jobTitle', label: '职称' },
      {
        prop: 'status',
        label: '状态',
        formatter: (val) => {
          switch(val) {
            case '正常': return '正常';
            case '冻结': return '冻结';
            default: return '未知';
          }
        }
      },
    ];
  } else if (activeModule.value === 'student') {
    viewData.value.list = [
      { prop: 'username', label: '用户名' },
      { prop: 'realName', label: '姓名' },
      { prop: 'sex', label: '性别', formatter: (val) => val === '男性' ? '男' : '女' },
      { prop: 'grade', label: '年级',formatter:row => row.grade ? `${row.grade}年级` : '已毕业' },
      { prop: 'classNum', label: '班级',formatter: row => row.grade ? `${row.classNum}班` : ''   },
      {
        prop: 'status',
        label: '状态',
        formatter: (val) => {
          switch(val) {
            case '正常': return '正常';
            case '冻结': return '冻结';
            default: return '未知';
          }
        }
      },
    ];
  } else {
    viewData.value.list = [
      { prop: 'username', label: '用户名' },
      { prop: 'realName', label: '姓名' },
      { prop: 'sex', label: '性别', formatter: (val) => val === '男性' ? '男' : '女' },
      // { prop: 'studentName', label: '绑定学生姓名' },
      // { prop: 'studentId', label: '绑定学生ID' },
      // { prop: 'grade', label: '年级',formatter: row => row.grade ? `${row.grade}年级` : '已毕业'},
      // { prop: 'classNum', label: '班级' ,formatter: row => row.grade ? `${row.classNum}班` : '' },
      {
        prop: 'status',
        label: '状态',
        formatter: (val) => {
          switch(val) {
            case '正常': return '正常';
            case '冻结': return '冻结';
            default: return '未知';
          }
        }
      },
      { prop: 'bindingCount', label: '绑定学生个数' },
      {
        label: '绑定学生', prop: 'studentDisplay'
      }
    ];
  }

  visible1.value = true;
};

// 删除单条数据
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除该${moduleNames[activeModule.value]}数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteUser(activeModule.value, row.id);
    ElMessage.success('删除成功');
    getData();
  }).catch(() => {});
};


const fetchStudentName = async (binding, index) => {
  try {
    const res = await getStudentById(binding.studentId);
    if (res.data) {
      rowData.value.bindings[index].studentName = res.data;
    } else {
      rowData.value.bindings[index].studentName = '无对应学生';
    }
  } catch (e) {
    rowData.value.bindings[index].studentName = '无对应学生';
  }
};


const addBinding = () => {
  rowData.value.bindings.push({ studentId: '', studentName: '' });
};

const removeBinding = (index: number) => {
  rowData.value.bindings.splice(index, 1);
};


// 初始化加载数据
getData();
</script>

<style scoped>
.module-selector {
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  padding: 15px;
  background: #fff;
  margin-bottom: 15px;
  border-radius: 4px;
}

.container {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  position: relative;
}

.toolbar-container {
  margin: 20px 0;
  text-align: right;
}

.el-table {
  margin-bottom: 15px;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 15px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
